package models;

import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

import play.data.validation.Required;
import play.db.jpa.Model;
import utils.models.CloneableForJSON;

@Entity
public class Post extends Model implements CloneableForJSON<Post>{
	@Required
	public String title;
	
	@Required
	public String content;
	
	@Required
	@ManyToOne(optional = false)
	public Author author;
	
	@Required
	@ManyToOne(optional = false)
	public Category category;
	
	@Required
	public Date dateUpdated;
	
	@OneToMany(mappedBy="post",cascade=CascadeType.ALL)
    public Set<Comment> comments;
	
	public Integer getNumberOfComments(){
		List<Comment> comments = Comment.find("byPostLike", this).fetch();
		return comments.size();
	}
	
	public String toString(){
		return title;
	}

	@Override
	public Post cloneForJSON() {
		Post clonedPost = new Post();
		clonedPost.id = this.id;
		clonedPost.title = this.title;
		clonedPost.content = this.content;
		clonedPost.author = this.author;
		clonedPost.category = this.category;
		clonedPost.dateUpdated = this.dateUpdated;
		Set<Comment> clonedComments = new LinkedHashSet<Comment>();
		for(Comment comment: this.comments){
			clonedComments.add(comment.cloneForJSON());
		}
		clonedPost.comments = clonedComments;
		return clonedPost;
	}
}